package com.ywk.miaohsa.controller;

import com.ywk.miaohsa.domain.MiaoshaOrder;
import com.ywk.miaohsa.domain.MiaoshaUser;
import com.ywk.miaohsa.rabbitmq.MQSender;
import com.ywk.miaohsa.rabbitmq.message.MiaoshaMessage;
import com.ywk.miaohsa.redis.GoodsKey;
import com.ywk.miaohsa.redis.OrderKey;
import com.ywk.miaohsa.redis.RedisService;
import com.ywk.miaohsa.result.CodeMsg;
import com.ywk.miaohsa.result.Result;
import com.ywk.miaohsa.service.GoodsService;
import com.ywk.miaohsa.service.MiaoshaService;
import com.ywk.miaohsa.service.OrderService;
import com.ywk.miaohsa.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/miaosha")
public class MiaoshaController implements InitializingBean {
    private static Logger log = LoggerFactory.getLogger(MiaoshaController.class);


    @Autowired
    GoodsService goodsService;

    @Autowired
    RedisService redisService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;

    @Autowired
    MQSender mqSender;

    private HashMap<Long, Boolean> localOverMap =  new HashMap<Long, Boolean>();

    /**
     * 系统初始化
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //将商品库存刷到缓存
        List<GoodsVo> goodsList=goodsService.getGoodsList();
        if(goodsList == null){
            return;
        }
        for (GoodsVo goodsVo : goodsList){
            redisService.set(GoodsKey.getMiaoshaGoodsStock,goodsVo.getId()+"",goodsVo.getStockCount());
            localOverMap.put(goodsVo.getId(), false);
        }
    }

    @RequestMapping(value="/do_miaosha", method=RequestMethod.POST)
    @ResponseBody
    public Result<Integer> miaosha(MiaoshaUser user,@RequestBody Map<String,Long> param) {
        if(user==null){
            Result.error(CodeMsg.SESSION_ERROR);
        }
        long goodsId=param.get("goodsId");
        //内存标记，减少redis的访问
        boolean over=localOverMap.get(goodsId);
        if (over) {
            return Result.error(CodeMsg.MIAO_SHA_OVER);
        }
        //判断是否已经秒杀到了
        MiaoshaOrder miaoshaOrder=orderService.getMiaoshaOrderByUserIdGoodsId(user.getId());
        if(miaoshaOrder != null){
            return Result.error(CodeMsg.REPEATE_MIAOSHA);
        }
        //预减库存
        long stock=redisService.decr(GoodsKey.getMiaoshaGoodsStock,goodsId+"");
        if(stock < 0){
            localOverMap.put(goodsId,true);
            return Result.error(CodeMsg.MIAO_SHA_OVER);
        }
        //入队列
        MiaoshaMessage message=new MiaoshaMessage();
        message.setUser(user);
        message.setGoodsId(goodsId);
        mqSender.sendMiaoshaMessage(message);
        return Result.success(0);
    }

    /**
     * 秒杀成功，生成订单
     * @param user
     * @return
     */
    @RequestMapping(value="/result", method=RequestMethod.GET)
    @ResponseBody
    public Result<Long> miaoshaResult(MiaoshaUser user) {
        if (user == null) {
            return Result.error(CodeMsg.SESSION_ERROR);
        }
        long res=miaoshaService.getMiaoshaResult(user.getId());
        log.info("执行miaoshaResult()，试图获取订单:"+res);
        return Result.success(res);
    }

}
